/**
 * 用户Store
 */
import { defineStore } from '../index'
import { getUserInfo as fetchUserInfo } from '../../api/login'
import { UserDataResponse } from '../../models/LoginModel'

// 用户信息接口
export interface UserInfo {
  id?: string
  phone?: string
  nickname?: string
  realName?: string
  avatar?: string
  token?: string
  role?: number  // 1-求职者 2-招聘者
  sex?: number
  email?: string
  birthday?: string
  country?: string
  province?: string | null
  city?: string | null
  district?: string | null
  description?: string
  startWorkDate?: string
  graduationYear?: number
  [key: string]: any  // 支持其他扩展字段
}

// State类型
interface UserState {
  userInfo: UserInfo
}

// Getters类型
interface UserGetters {
  isLogin: (state: UserState) => boolean
  userId: (state: UserState) => string
  userPhone: (state: UserState) => string
  userNickname: (state: UserState) => string
  userAvatar: (state: UserState) => string
  token: (state: UserState) => string
}

// Actions类型
interface UserActions {
  setUserInfo: (info: UserInfo) => void
  updateUserInfo: (info: Partial<UserInfo>) => void
  clearUserInfo: () => void
  setToken: (token: string) => void
  getUserInfo: () => Promise<boolean>
  logout: () => Promise<void>
  connectWebSocket: () => Promise<void>
  disconnectWebSocket: () => Promise<void>
}

/**
 * 用户Store定义
 */
export const useUserStore = defineStore<UserState, UserGetters, UserActions>({
  id: 'user',
  
  // 状态
  state: () => ({
    userInfo: {}
  }),
  
  // 计算属性
  getters: {
    // 是否已登录
    isLogin(state: UserState): boolean {
      return !!(state.userInfo.token || state.userInfo.id)
    },
    
    // 用户ID
    userId(state: UserState): string {
      return state.userInfo.id || ''
    },
    
    // 用户手机号
    userPhone(state: UserState): string {
      return state.userInfo.phone || ''
    },
    
    // 用户昵称
    userNickname(state: UserState): string {
      return state.userInfo.nickname || ''
    },
    
    // 用户头像
    userAvatar(state: UserState): string {
      return state.userInfo.avatar || ''
    },
    
    // 用户token
    token(state: UserState): string {
      return state.userInfo.token || ''
    }
  },
  
  // 方法
  actions: {
    /**
     * 设置用户信息
     */
    setUserInfo(info: UserInfo) {
      this.$state.userInfo = { ...info }
    },
    
    /**
     * 更新用户信息（部分更新）
     */
    updateUserInfo(info: Partial<UserInfo>) {
      this.$state.userInfo = {
        ...this.$state.userInfo,
        ...info
      }
    },
    
    /**
     * 清除用户信息（退出登录）
     */
    clearUserInfo() {
      this.$state.userInfo = {}
    },
    
    /**
     * 设置token
     */
    setToken(token: string) {
      this.$state.userInfo = {
        ...this.$state.userInfo,
        token
      }
    },
    
    /**
     * 获取用户信息
     * @returns Promise<boolean> - 成功返回true，失败返回false
     */
    async getUserInfo(): Promise<boolean> {
      try {
        // 调用API获取用户信息
        const userData: UserDataResponse = await fetchUserInfo()
        
        // 将API返回的数据映射到UserInfo
        const userInfo: UserInfo = {
          id: userData.id,
          phone: userData.phone,
          nickname: userData.nickName,
          realName: userData.realName,
          avatar: userData.face,
          role: userData.role,
          sex: userData.sex,
          email: userData.email,
          birthday: userData.birthday,
          country: userData.country,
          province: userData.province,
          city: userData.city,
          district: userData.district,
          description: userData.description,
          startWorkDate: userData.startWorkDate,
          graduationYear: userData.graduationYear,
          token: this.$state.userInfo.token // 保留当前token
        }
        
        // 更新store中的用户信息
        this.$state.userInfo = userInfo
        
        console.log('用户信息获取成功:', JSON.stringify(userInfo))
        return true
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 获取失败，清除用户信息
        this.clearUserInfo()
        return false
      }
    },
    
    /**
     * 退出登录：清空本地token与用户信息，并清除持久化
     */
    async logout(): Promise<void> {
      try {
        // 断开 WebSocket
        await this.disconnectWebSocket()
        // 清空用户信息
        this.$reset()
      } catch (e) {
        // 保底清空
        this.$state.userInfo = {}
      }
    },

    /**
     * 连接 WebSocket（通过 chatStore）
     */
    async connectWebSocket(): Promise<void> {
      const token = this.$state.userInfo.token
      const roleType = this.$state.userInfo.role || 0
      
      if (!token) {
        console.log('[UserStore] token 为空，跳过 WebSocket 连接')
        return
      }

      if (roleType !== 1 && roleType !== 2) {
        console.log('[UserStore] 无效的角色类型，跳过 WebSocket 连接')
        return
      }

      try {
        console.log('[UserStore] 开始连接 WebSocket...')
        
        // 获取 chatStore（延迟导入避免循环依赖）
        const { useChatStore } = await import('./chat')
        const chatStore = useChatStore()
        
        // 通过 chatStore 连接 WebSocket
        await chatStore.connectWebSocket(token, roleType)
        
        console.log('[UserStore] WebSocket 连接完成')
      } catch (error) {
        console.error('[UserStore] WebSocket 连接失败:', error)
      }
    },

    /**
     * 断开 WebSocket（通过 chatStore）
     */
    async disconnectWebSocket(): Promise<void> {
      try {
        console.log('[UserStore] 开始断开 WebSocket 连接...')
        
        // 获取 chatStore（延迟导入避免循环依赖）
        const { useChatStore } = await import('./chat')
        const chatStore = useChatStore()
        
        // 通过 chatStore 断开 WebSocket
        await chatStore.disconnectWebSocket()
        
        console.log('[UserStore] WebSocket 断开连接完成')
      } catch (error) {
        console.error('[UserStore] WebSocket 断开连接失败:', error)
      }
    }
  },
  
  // 持久化配置
  persist: {
    enabled: true,
    key: 'user_store',
    paths: ['userInfo']  // 只持久化userInfo字段
  }
})

